import { DialogRef, useDialog } from "../../../utils/react-use/useDialog";
import { message, Modal } from "tea-component";
import React from "react";
import { AddFriendForm, FormValue } from "./AddFriendForm";
import { addFriends, sendMsg } from "../../../api";
import Toast from "../../../components/toast/Toast";
import { useSettingConfig } from "../../../utils/react-use/useSettingConfig";
import { useDispatch, useSelector } from "react-redux";
import { updateUserInfo } from "../../../store/actions/user";
import { aesEncry } from "../../../utils/tools";

export interface CreateGroupRecordType {
  userId: string;
}

export const AddFriendDialog = (props: {
  onSuccess?: () => void;
  dialogRef: DialogRef<CreateGroupRecordType>;
}): JSX.Element => {
  const { onSuccess, dialogRef } = props;
  const { userId:selfUserId } = useSettingConfig();
  const dispatch = useDispatch();
  const {userId,addFriendID,addFriendName} = useSelector((state: State.RootState) =>state.userInfo);
  const [visible, setShowState, defaultForm] = useDialog<CreateGroupRecordType>(
    dialogRef,
    {}
  );
  const onclean =()=>{
    dispatch(updateUserInfo({userId,addFriendID:""}))
  }
  const onClose = () => {
    onclean();
    setShowState(false);
  }

  const success = () => {
    onSuccess();
    onClose();
  };
  const request = require('request');
  const onSubmit = async (formData: FormValue) => {
      if(formData.userId==addFriendName){
        formData.userId = addFriendID;
        try {
          const res = await addFriends(formData);
          message.success({
            style:{top:"50%"},content: "好友请求已发送"
          })
        } catch (e) {
          message.error({
              content: "好友请求发送失败"
          })
        }
        return;
      }
      request.post(Toast.defaultser+'/api/app/member/addFriendByPc', {
        headers: {
          Authorization: Toast.token,
        },
        json:{
          addSource:"AddSource_Type_pc",
          username:formData.userId,addWording:formData.helloMsg,remark:formData.remark
        }
      }, (error, res, body) => {
          if (error) {
            message.error({ style:{top:"50%"},content: error});
            return
          }
          console.log(body);
          if(body.code==200){
            message.success({
              style:{top:"50%"},content: body.message
            });
            if(body.data?.code == 0){
              sendMsg({
                convId: body.data.imUserId, convType: 1,
                messageElementArray: [{
                    elem_type: 0,
                    text_elem_content:  aesEncry('我们已经是好友，可以开始聊天了')
                },],
                userId: selfUserId,
              });
            }
          }else{
            message.error({style:{top:"50%"},content: body.message });
          }
      });
  };

  return (
    <Modal  className="dialog" disableEscape visible={visible} onClose={onClose} caption="添加好友">
      <Modal.Body>
        <AddFriendForm onSubmit={onSubmit} onSuccess={success}  onClose={onClose} uname={addFriendName} />
      </Modal.Body>
    </Modal>
  );
};
